import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:fsharing/core/models/store_index.dart';
import 'package:fsharing/core/viewmodels/app_model.dart';
import 'package:fsharing/core/viewmodels/pages/home/news_model.dart';
import 'package:fsharing/core/viewmodels/pages/home/news_query_model.dart';
import 'package:fsharing/core/viewmodels/view_model.dart';
import 'package:fsharing/main.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class NewsItemPage extends StatelessWidget {
  final String linkType;
  final String title;

  NewsItemPage({
    Key key,
    @required this.linkType,
    @required this.title,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProxyProvider<NewsModel, NewsQueryModel>(
      create: (context) => NewsQueryModel(
        Provider.of(context, listen: false),
        Provider.of<AppStoreModel>(context, listen: false).currentStoreId,
        linkType,
      ),
      update: (context, newsModel, model) => model..queryKey = newsModel.queryKey,
      child: Consumer<NewsQueryModel>(
        builder: (context, model, child) {
          switch (model.viewState) {
            case ViewState.busy:
              return Center(
                child: CircularProgressIndicator(),
              );
            case ViewState.error:
              return Center(
                child: Text(model.errorMessage),
              );
            case ViewState.success:
              return _SuccessWidget(title: title);
            default:
              return Container();
          }
        },
      ),
    );
  }
}

class _SuccessWidget extends StatelessWidget {
  final String title;
  final RefreshController _refreshController = RefreshController();

  _SuccessWidget({
    Key key,
    @required this.title,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    NewsQueryModel model = Provider.of(context, listen: false);
    final list = model.list;
    final newsQuery = model.newsQuery;
    return Scaffold(
      body: Column(
        children: <Widget>[
          Container(
            alignment: Alignment.centerLeft,
            padding: EdgeInsets.only(left: 16),
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage('assets/images/home/img_news_header.png'),
              ),
            ),
            height: 45,
            child: Text(
              title,
              style: TextStyle(fontSize: 15),
            ),
          ),
          Expanded(
            child: Theme(
              data: lightTheme(),
              child: Material(
                child: SmartRefresher(
                  controller: _refreshController,
                  child: ListView.separated(
                    padding: EdgeInsets.all(12),
                    itemBuilder: (context, index) {
                      return _NewsItemWidget(
                        link: list[index],
                      );
                    },
                    separatorBuilder: (context, index) {
                      return Divider(
                        height: 12,
                      );
                    },
                    itemCount: list.length,
                  ),
                  enablePullDown: false,
                  enablePullUp: newsQuery.newsList.length == 10,
                  onLoading: () => _onLoadData(context),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  void _onLoadData(BuildContext context) async {
    NewsQueryModel model = Provider.of(context, listen: false);
    await model.loadData();
    _refreshController.loadComplete();
  }
}

class _NewsItemWidget extends StatelessWidget {
  final Link link;

  _NewsItemWidget({
    Key key,
    this.link,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return InkWell(
      child: Row(
        children: <Widget>[
          ClipRRect(
            borderRadius: BorderRadius.circular(4),
            child: CachedNetworkImage(
              imageUrl: link.image,
              width: 68,
              height: 68,
              fit: BoxFit.fill,
            ),
          ),
          Expanded(
            child: Container(
              height: 60,
              margin: EdgeInsets.only(left: 8),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text(
                    link.title,
                    style: TextStyle(fontSize: 16),
                    overflow: TextOverflow.ellipsis,
                    maxLines: 2,
                  ),
                  Row(
                    children: <Widget>[
                      Expanded(
                        child: Text(
                          link.creatorName ?? '--',
                          style: TextStyle(color: Colors.grey, fontSize: 12),
                        ),
                      ),
                      Text(
                        link.createTime ?? '--:--:--',
                        style: TextStyle(color: Colors.grey, fontSize: 12),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
      onTap: () {
        _onItemClicked(context);
      },
    );
  }

  void _onItemClicked(BuildContext context) {
    Navigator.of(context).pushNamed('/news/detail', arguments: link);
  }
}
